import java.util.Arrays;


public class Prim {
    public static void main(String[] args) {
        int max = 10000;
        char[] data = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
        int verxs = data.length;
        int[][] weight = new int[][]{
                {max, 5, 7, max, max, max, 2},
                {5, max, max, 9, max, max, 3},
                {7, max, max, max, 8, max, max},
                {max, 9, max, max, max, 4, max},
                {max, max, 8, max, max, 5, 4},
                {max, max, max, 4, 5, max, 6},
                {2, 3, max, max, 4, 6, max}
        };
        MGraph mGraph = new MGraph(verxs);
        MinTree minTree = new MinTree();
        minTree.createGraph(mGraph, data, weight);
        minTree.prim(mGraph, 5);

    }
}

class MGraph {
    int verxs; //图的节点个数
    char[] data; //节点数据
    int[][] weight;

    public MGraph(int verxs) {
        this.verxs = verxs;
        data = new char[verxs];
        weight = new int[verxs][verxs];
    }
}

class MinTree {
    public void createGraph(MGraph graph, char[] data, int[][] weight) {
        for (int i = 0; i < graph.verxs; i++) {
            graph.data[i] = data[i];
            for (int j = 0; j < graph.verxs; j++) {
                graph.weight[i][j] = weight[i][j];
            }
        }
    }

    public void showGraph(MGraph graph) {
        for (int[] link : graph.weight) {
            System.out.println(Arrays.toString(link));
        }
    }

    //v表示最小生成树的顶点
    public void prim(MGraph graph, int v) {
        // 表示已经被访问过的节点
        boolean[] visited = new boolean[graph.verxs];
        visited[v] = true;
        int h1 = -1;  //用h1和h2记录被连接的节点的下标
        int h2 = -1;
        int minWeight = 10000;
        int value = 0;
        //生成n-1条边
        for (int k = 1; k < graph.verxs; k++) {

            //循环visited图,寻找到一个未访问过的节点的访问最小路径
            for (int i = 0; i < visited.length; i++) {
                for (int j = 0; j < visited.length; j++) {
                    if (visited[i] && visited[j] == false && graph.weight[i][j] < minWeight) {
                        minWeight = graph.weight[i][j];
                        h1 = i;
                        h2 = j;
                    }
                }
            }
            value += minWeight;
            System.out.println("第" + k + "条边<" + graph.data[h1] + "," + graph.data[h2] + "> , 权值:" + minWeight);
            visited[h2] = true;
            minWeight = 10000;
        }
        System.out.println("总路径权值: " + value);
    }
}
